<template>
  <div class="system-user-container">
    <el-card shadow="hover">
      <div class="system-user-search mb15">
        <el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="关键字" prop="keywords">
            <el-input
                v-model="tableData.param.keywords"
                placeholder="关键字"
                clearable
                size="default"
            />
          </el-form-item>
          <el-form-item>
            <el-button size="default" type="primary" class="ml10" @click="groupList">
              <el-icon>
                <ele-Search/>
              </el-icon>
              查询
            </el-button>
            <el-button size="default" type="success" class="ml10" @click="handleEditGroup({})">
              <el-icon>
                <ele-FolderAdd/>
              </el-icon>
              新增分组
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
          default-expand-all
          :data="tableData.data"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          row-key="pid"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="name" label="分组名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="desc" label="分组描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="desc" label="启用" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">启用</el-tag>
            <el-tag  v-if="scope.row.status === 1" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" text type="primary" @click="handleEditGroup(scope.row)">修改</el-button>
            <el-button size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="tableData.total>0"
          :total="tableData.total"
          v-model:page="tableData.param.pageNum"
          v-model:limit="tableData.param.pageSize"
          @pagination="groupList"
      />
    </el-card>
    <EditGroup ref="editGroupRef" :act-type="actType" @callback="groupList"/>
  </div>
</template>

<script lang="ts">
import {toRefs, reactive, onMounted, ref, defineComponent, getCurrentInstance} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {Search} from '@element-plus/icons-vue'
import EditGroup from "/@/views/system/group/component/editGroup.vue";
import {deleteGroup, getGroupList} from "/@/api/system/group";

interface TableDataState {
  ids: number[];
  tableData: {
    data: any[];
    total: number;
    loading: boolean;
    param: {
      pageNum: number;
      pageSize: number;
      keywords: string;
    };
  };
}

export default defineComponent({
  name: 'systemGroup',
  components: {EditGroup},
  setup() {
    const {proxy} = getCurrentInstance() as any;
    const actType = ref('add')
    const editGroupRef = ref();
    const queryRef = ref();
    const search = Search
    const state = reactive<TableDataState>({
      ids: [],
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          pageNum: 1,
          pageSize: 10,
          keywords: '',
        },
      },
    });
    // 初始化表格数据
    const initTableData = () => {
      groupList();
    };
    const groupList = () => {
      getGroupList(state.tableData.param).then((res: any) => {
        state.tableData.data = proxy.handleTree(res.data.list ?? [], "id", "pid");
        state.tableData.total = res.data.total;
      });
    };
    const handleEditGroup = (row: any) => {
      if(row?.id) {
        actType.value = 'edit'
        editGroupRef.value.openDialog(row);
      } else {
        actType.value = 'add'
        editGroupRef.value.openDialog({});
      }
    };
    const onRowDel = (row: any) => {
      let msg = '你确定要删除所选用户？';
      let ids: number[] = [];
      if (row) {
        msg = `此操作将永久删除用户：“${row.userName}”，是否继续?`
        ids = [row.id]
      } else {
        ids = state.ids
      }
      if (ids.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return
      }
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            deleteGroup(ids).then(() => {
              ElMessage.success('删除成功');
              groupList();
            })
          })
          .catch(() => {
          });
    };
    // 分页改变
    const onHandleSizeChange = (val: number) => {
      state.tableData.param.pageSize = val;
    };
    // 分页改变
    const onHandleCurrentChange = (val: number) => {
      state.tableData.param.pageNum = val;
    };
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    // 多选框选中数据
    const handleSelectionChange = (selection: any[]) => {
      state.ids = selection.map(item => item.id)
    };
    return {
      actType,
      queryRef,
      editGroupRef,
      handleEditGroup,
      onRowDel,
      onHandleSizeChange,
      onHandleCurrentChange,
      groupList,
      search,
      handleSelectionChange,
      ...toRefs(state),
    };
  },
});
</script>
